/**
 * Created by Administrator on 2017/3/29.
 */
app.controller('detailCtrl',
['$scope','$location','$routeParams','$http','$sce','$rootScope','$anchorScroll', function ($scope,$location,$routeParams,$http,$sce,$rootScope,$anchorScroll) {
    //loading提示
    $("#globalLoading").css({opacity:'1', top:'10rem'});

    //获取详情 需要根据fileId
    var articleId =$routeParams.fileId;
    console.log("artarticleId")
    console.log(articleId)
    // var articleId=174;
    $http.jsonp(articleDetailContenUrl+'articleId='+articleId+'&jsoncallback=JSON_CALLBACK'
    ).success(function(data,header,config,status){
        $scope.detailData=data;//获取返回对象
        //添加类型方便评论时判断
        console.log("detailData")
        console.log($scope.detailData)
        //是否关闭该篇稿件评论功能
        if(data== "" || data == undefined ||data == null){
            $scope.currentDiscussClosed=0;
        }else{
            $scope.currentDiscussClosed=data.discussClosed;
        }

        //// 组图图片
        //var regs=/<!--IMAGES#1-->/gi;
        //
        //var multiPics="<div style='width:100%;overflow: hidden;padding:2px'>";
        //$scope.detailData.content=$scope.detailData.content.replace(regs,function () {
        //
        //    for(var j=0;j<data.images[0].imagearray.length;j++){
        //        console.log(data.images[0].imagearray[j].imageUrl);
        //        multiPics+='<img src="'+data.images[0].imagearray[j].imageUrl+'" style="float:left;width: 100%;margin-left: 1%"><p style="margin: 15px 0">'+data.images[0].imagearray[j].summary+'</p>'
        //    }
        //    multiPics+="</div>";
        //    return multiPics;
        //});
        //console.log(multiPics)
        //$scope.trustHtml = $sce.trustAsHtml(multiPics);


        var datas= $scope.detailData.content;//获取动态模板
    if(datas.indexOf("body")!=-1){
        var indexA=datas.indexOf("<body>");
        var indexB=datas.indexOf("<\/body>");
        var detailDatass=datas.substring((indexA+6) ,indexB);


   }else{
         detailDatass=$scope.detailData.content
   }
        // 非组图图片
        var i=0;
        var reg=/<!--IMAGEARRAY#[0-9]{1,}-->/gi;
        detailDatass=detailDatass.replace(reg,function () {
          return '<img style="margin-bottom:1.333rem" src="'+data.images[0].imagearray[i++].imageUrl+'">';
        });

        $('img').parent().css({'textIndent':'0'});
        // console.log(detailDatass)
        //后去除去body标签内容
        $scope.con=detailDatass;
        $scope.trustHtml = $sce.trustAsHtml($scope.con);


    // 组图图片内容问题
        if($scope.detailData.content.indexOf('<!--IMAGES#1-->')!=-1){
            var regs=/<!--IMAGES#1-->/gi;
            var multiPics="<div style='width:100%;overflow: hidden;padding:2px'>";
            $scope.detailData.content=$scope.detailData.content.replace(regs,function () {

                for(var j=0;j<data.images[0].imagearray.length;j++){
                    console.log(data.images[0].imagearray[j].imageUrl);
                    multiPics+='<img src="'+data.images[0].imagearray[j].imageUrl+'" style="float:left;width: 100%;margin-left: 1%;margin-bottom:1.333rem"><p style="margin: 15px 0">'+data.images[0].imagearray[j].summary+'</p>'
                }
                multiPics+="</div>";
                return multiPics;
            });
            console.log(multiPics)
            $scope.trustHtml = $sce.trustAsHtml(multiPics);
        }


        //获取相关稿件
        $scope.Hdata=$scope.detailData.related;
       //相关推荐条数大于1添加下划线
        if($scope.detailData.related.length>1){
            $scope.HdataDeatilBorder=true;
        }

        //loading提示
        $("#globalLoading").animate({
            top:'20px',
            opacity:'0'
        },500);

    }).error(function(data,header,config,status){
    });

    // 详情页字体放大
    var detaiScalFontSizeNum=1;
    $scope.fontMagination='static/11.png';
    var flag=true;
    $scope.detaiScalFontSize=function () {
        //最大到2.5em
        if(detaiScalFontSizeNum>=1.8){
            flag=false;
            $scope.fontMagination='static/46.png';
        }else if(detaiScalFontSizeNum<=1){
            flag=true;
            $scope.fontMagination='static/11.png';
        }
       if(flag){
           detaiScalFontSizeNum+=0.1;
       }else if(!flag){
           detaiScalFontSizeNum-=0.1;
       }
       for(var i=0;i<$('.detailConStyle').children().length;i++){
           $('.detailConStyle').children().eq(i).css("fontSize",detaiScalFontSizeNum+"em");
       }
        for(var i=0;i<$('.detailConStyle').children().length;i++){
            $('.detailConStyle').children().eq(i).css("lineheight",detaiScalFontSizeNum+"em");
        }

    };

    $rootScope.detailAddPraseImag="static/13.png";
   //点赞 不需要这些userID=22,userOtherID=111,siteID=1,
    $scope.detailAddPrase=function () {
        if(doGetCookie('article'+articleId)){
            alert("该篇稿件您已经点赞，请不要重复点赞");
            return
        }else{
            $scope.detailData.countPraise++;
            console.log("useid");
            console.log($scope.uid_fouNder);
            var userID=$rootScope.uid_fouNder;
            $rootScope.detailAddPraseImag="static/14.png";
            var id=articleId,type=0,eventType=1,channel=1;
            //提交回复
            $.ajax({
                type: "post",
                url: detailPrasieUrl,
                data:{
                    "id": id,
                    "type": type,
                    "eventType": eventType,
                    "channel":channel
                },
                dataType : "jsonp",
                jsonp: "jsoncallback",
                jsoncallback:"jsoncallback",
                success: function(data){
                    setCookie('article'+articleId,1)
                },
                error: function(){
                    // alert("点赞失败");
                }
            });
        }

    };
    $rootScope.detailAddStorImag="static/15.png";
    //收藏 需要userid
    $scope.detailAddStor=function () {
        if(uid_fouNder){
            var userID=uid_fouNder;
            $rootScope.detailAddStorImag="static/16.png";
            var userID=userID,siteID=1,type=0,id=articleId,channel=1;
            //提交回复
            $http.jsonp(artDetailAddStorUrl+'userID='+userID+'&siteID='+siteID+'&type='+type+'&id='+id+'&channel'+channel+'&jsoncallback=JSON_CALLBACK'
            ).success(function(data,header,config,status){
                console.log("收藏成功");
            }).error(function(data,header,config,status){

            });
        }else{
            alert("请登录后收藏");
            $scope.h5Jump('http://59.108.92.239:9081/SSOv2/user/ssoLogin?code=yxapp&redirectUrl=http://59.108.92.239/amucsite/pad/sso/setCookie.html?&isAppType=app&anyUrl=http://59.108.92.239/amucsite/pad/index.html#/detail/'+articleId);
            //ssologin()

        }

    };

/**
 * 评论相同活动视频直播完全相同部分
 * ***/


    //获取最新评论id=3969
    $scope.getNewCom=function () {
         $scope.commeInputs=siteConfig.defaultHint;
         $http.jsonp(newComment+'id='+articleId+'&siteId=1&lastFileId=0&page=0&source='+artSource+'&jsoncallback=JSON_CALLBACK'
         ).success(function(data,header,config,status){
             console.log("新评论");
              console.log(data);
              // 是否还有更多评论
              $scope.hasMorCom=data.hasMore;
              $scope.newCommenCon=data.list;
             console.log("新评内容");
             console.log($scope.newCommenCon);
             $scope.newComCounts=data.totalCount;
             console.log("新评论数量");
             console.log($scope.newComCounts);
         }).error(function(data,header,config,status){

         });
    };


    //获取 热门评论'+articleId+' 测试3969
    $scope.getHotCom=function () {
         $http.jsonp(hotComment+'id='+articleId+'&siteId=1&source='+artSource+'&jsoncallback=JSON_CALLBACK'
         ).success(function(data,header,config,status){
             // 是否还有更多评论
             //获取评论
             $scope.commenCon=data.list;
             console.log("热门评论");
             console.log($scope.commenCon);
             // $scope.hotComCounts=data.totalCount;
         }).error(function(data,header,config,status){
         });
    };

    // 加载详情页时先加载最新评论一次，顺序问题,不能放getNewCom方法前以下
    // 应该是 $scope.getHotCom() newCom要改为'+articleId+'
    //$scope.getNewCom();
    //$scope.getHotCom();

    //获取全局配置信息
    $scope.getCommentInfo=function(){
        $http.jsonp(commInfo+'&jsoncallback=JSON_CALLBACK'
        ).success(function(data,header,config,status){
            console.log("全局评论信息");
            console.log(data);
            $scope.siteConfig=data.siteConfig.discuss;
            //评论框提示语
            siteConfig.defaultHint=$scope.siteConfig.defaultHint;
            //官方评论用户名
            siteConfig.defaultName=$scope.siteConfig.defaultName;
            $scope.defaultName=$scope.siteConfig.defaultName;
            //官方评论头像
            siteConfig.defaultIcon=$scope.siteConfig.defaultIcon;
            $scope.siteConfigDefaultIcon=$scope.siteConfig.defaultIcon;
            console.log("官方用户名");
            console.log($scope.defaultName);
            //是否关闭全站评论功能
            $scope.siteConfigAuditType=$scope.siteConfig.auditType;
            //全局评论颜色问题
            $scope.commStyleColor=$scope.siteConfig.styleColor;
            commentStyle=$scope.commStyleColor;
            $rootScope.changeComStyle();

            //评论是否允许上传图片
            $scope.commentShowPic=data.siteConfig.discuss.showPic;

            //获取最新和热门评论
            $scope.getNewCom();


           //setTimeout(function () {

           //},1000)
        }).error(function(data,header,config,status){

        });


    };
    $scope.getCommentInfo();

    //点击评论数，跳转
    $scope.commentJump=function(){
        if($scope.newCommenCon.length>0){
            var scrollDistance=$("#newComCon").offset().top-60;
            $("body").animate({scrollTop:scrollDistance}, 300);
        }else if($scope.commenCon.length>0){
            var scrollDistance=$("#commenCon").offset().top-60;
            $("body").animate({scrollTop:scrollDistance}, 300);
        }else{
            return
        }
    };


    //弹出模态框
    $scope.showModeAndRepley=function ($event) {

        //if($rootScope.uid_fouNder){

            $('#commentModle').css('display',"block");
            $("#commentArea").css('display',"block");

             $("#comInput").focus();
             $("#comInput").attr("placeholder","请输入内容:");
            $("#comm_text_footer").css('display',"none");
       //}else{
       //     window.location='http://172.19.32.122:9081/SSOv2/user/login_app';
       // }
        $scope.parentId=0;

    };
    //取消模态框
    $scope.cancelCom=function () {
        //添加input图片上传的的占位
        $("#uploadImagForm").css({display:'block'});
        //清除选中图片
        $(".imgCont").children().remove();
        //清除上传图片的对象
        window.uploadFile="";
        $("#comInput").val("");
        $('#commentModle').css('display',"none");
        $("#commentArea").css('display',"none");
        $("#comm_text_footer").css('display',"block");
    }

    //回复评论
    $scope.replayCom=function (parentId,userName,ParentUserID) {

        $('#commentModle').css('display',"block");
        $("#commentArea").css('display',"block");
        $("#comm_text_footer").css('display',"none");
        $("#comInput").attr("placeholder","@"+userName+":");
        // 提交评论使用
         $scope.parentId=parentId;
         $scope.userName=userName;
        $scope.ParentUserID=ParentUserID;

    };

    // 发送评论
    $scope.sendCom=function () {
       if(!window.uploadFile){
           //只提交文字评论
            var sendMesg=$("#comInput").val();
            console.log("评论信息");
            console.log(sendMesg);
            var logUserId=uid_fouNder;
            var LogUserName=username_fouNder;
            //匿名评论
            if(!uid_fouNder){
                logUserId=0;
                LogUserName="触屏用户";
            }
            var topicTitle= $scope.detailData.title;
            var siteID = 1, rootID = articleId, parentID = $scope.parentId, parentUser = $scope.userName,
                parentUserID = $scope.ParentUserID, topic =topicTitle, userID=logUserId
                , userName=LogUserName, type = 0,content=sendMesg;

            //提交回复
            $.ajax({
                type: "post",
                url: sentComent,
                data:{
                    "siteID": siteID,
                    "rootID": articleId,
                    "parentID": parentID,
                    "parentUser": parentUser,
                    "parentUserID": parentUserID,
                    "topic": topic,
                    "userID": userID,
                    "userName": userName,
                    "type": type,
                    "content":content,
                    "channel":1,
                    "sourceType":artSource

                },
                dataType : "json",
                //jsonp: "jsoncallback",
                //jsoncallback:"jsoncallback",
                success: function(data){
                        console.log(data);
                        alert("评论成功！");
                        $scope.getNewCom();
                        console.log("发送内容为：");
                        console.log(sendMesg);
                        $("#comInput").val("");
                        $('#commentModle').css('display',"none");
                        $("#commentArea").css('display',"none");
                        $("#comm_text_footer").css('display',"block");
                        $('.up-section').each(function(el,value){
                            console.log("图片数组")
                            alert()
                            console.log(el)
                            console.log(value)
                            //arrFiles=[]
                            //imgArr=[]
                            loadImg();
                        });


                },
                error: function(){
                    alert("评论失败！2");
                    $("#comInput").val("");
                    $('#commentModle').css('display',"none");
                    $("#commentArea").css('display',"none");
                    $("#comm_text_footer").css('display',"block");
                }
            });
        }else{
           //即提交评论文字，又上传图片

           var imgUrl=window.uploadFile;
           console.log("提交的图片信息")
           console.log(imgUrl)

           //图片提交
           var formdata = new FormData();
           formdata.append("Filedata", imgUrl);
           formdata.append("siteID", 1);
           formdata.append("location", 0);
           formdata.append("userId", "0");
           formdata.append("fileType", "picture");
           formdata.append("uniqid", "B715C9A0-D580-46F2-ABD1-F244EA24C934");

           $.ajax({
               type:'POST',
               url: commUpload,
               processData: false,
               data: formdata,
               async:false,
               contentType: false,    //这个一定要写
               dataType:'json',
               success: function(result){
                   //成功后处理代码
                   //self.onSuccess(file, result);
                   //if(self.curUploadFile.length==0){
                   // 回调全部完成方法
                   //self.onComplete("全部完成");
                   console.log("上传成功");
                   console.log(result)
                   console.log("上传成功url");
                   var comimgUrl=JSON.parse(result).fileList[0].url;
                   console.log("comimgUrl")
                   console.log(comimgUrl);
                   setTimeout(function(){
                       var sendMesg=$("#comInput").val();
                       console.log("评论信息");
                       console.log(sendMesg);
                       var logUserId=uid_fouNder;
                       var LogUserName=username_fouNder;
                       //匿名评论
                       if(!uid_fouNder){
                           logUserId=0;
                           LogUserName="触屏用户";
                       }
                       var topicTitle= $scope.detailData.title;
                       var siteID = 1, rootID = articleId, parentID = $scope.parentId, parentUser = $scope.userName,
                           parentUserID = $scope.ParentUserID, topic =topicTitle, userID=logUserId
                           , userName=LogUserName, type = 0,content=sendMesg;

                       //提交回复
                       $.ajax({
                           type: "post",
                           url: sentComent,
                           data:{
                               "siteID": siteID,
                               "rootID": articleId,
                               "parentID": parentID,
                               "parentUser": parentUser,
                               "parentUserID": parentUserID,
                               "topic": topic,
                               "userID": userID,
                               "userName": userName,
                               "type": type,
                               "content":content,
                               "channel":1,
                               "sourceType":artSource,
                               "imgUrl":comimgUrl

                           },
                           dataType : "json",
                           //jsonp: "jsoncallback",
                           //jsoncallback:"jsoncallback",
                           success: function(data){
                               console.log(data);
                               alert("上传图片成功！");
                               $scope.getNewCom();
                               console.log("发送内容为：");
                               console.log(sendMesg);
                               //清空全局需要上传的图片对象
                               window.uploadFile=""
                               //添加input图片上传的的占位
                               $("#uploadImagForm").css({display:'block'});
                               //清除选中图片
                               $(".imgCont").children().remove();
                               $("#comInput").val("");
                               $('#commentModle').css('display',"none");
                               $("#commentArea").css('display',"none");
                               $("#comm_text_footer").css('display',"block");
                               $('.up-section').each(function(el,value){
                                   console.log("图片数组")
                                   alert()
                                   console.log(el)
                                   console.log(value)
                                   //arrFiles=[]
                                   //imgArr=[]
                                   loadImg();
                               });


                           },
                           error: function(){
                               alert("上传图片失败！2");
                               //清空全局需要上传的图片对象
                               window.uploadFile=""
                               //添加input图片上传的的占位
                               $("#uploadImagForm").css({display:'block'});
                               //清除选中图片
                               $(".imgCont").children().remove();
                               $("#comInput").val("");
                               $('#commentModle').css('display',"none");
                               $("#commentArea").css('display',"none");
                               $("#comm_text_footer").css('display',"block");
                           }
                       });
                },1000)
               },
               error: function(){
                   self.onFailure(file);
               }

           });

       }
    };


    $scope.lunchaMorChilCom=true;
    // 最新评论子评论
    //获取子评论加载更多更多内容 id为每条父评论的id号
    $scope.checkMorChildCom=function (id,index) {
        $scope.lunchaMorChilCom=false;

        $http.jsonp(replayComent+'id='+id+'&page=0&siteId=1&source=0&jsoncallback=JSON_CALLBACK'
        ).success(function(data,header,config,status){
            //点击查看更多子评论之前
            $scope.beforLoadMorChid=$scope.newCommenCon[index].topDiscuss.list;
            //点击查看更多子评论之后
            $scope.newCommenCon[index].topDiscuss.list=data.list;

            // 是否还有更多评论
            /*console.log("是否有更多")
             console.log(data.hasMore)*/
            $scope.hasNoChildMorCom={};
            $scope.hasChildMorCom={};
            if(data.hasMore){
                $scope.hasChildMorCom.index=true;
            }else{
                $scope.hasNoChildMorCom.index=true;

            }
            //获取评论
            // $scope.commenCon=data.list;
        }).error(function(data,header,config,status){
        });
    }

    $scope.hotlunchaMorChilCom=true;
    // 热门评论子评论
    //获取子评论加载更多更多内容 id为每条父评论的id号
    $scope.hotcheckMorChildCom=function (id,index) {
        $scope.hotlunchaMorChilCom=false;

        $http.jsonp(replayComent+'id='+id+'&page=0&siteId=1&source='+artSource+'&jsoncallback=JSON_CALLBACK'
        ).success(function(data,header,config,status){
            //点击查看更多子评论之前
            $scope.hotbeforLoadMorChid=$scope.commenCon[index].topDiscuss.list;
            //点击查看更多子评论之后
            $scope.commenCon[index].topDiscuss.list=data.list;

            // 是否还有更多评论
            /*console.log("是否有更多")
             console.log(data.hasMore)*/
            $scope.hothasNoChildMorCom={};
            $scope.hothasChildMorCom={};
            if(data.hasMore){
                $scope.hothasChildMorCom.index=true;
            }else{
                $scope.hothasNoChildMorCom.index=true;

            }
            //获取评论
            // $scope.commenCon=data.list;
        }).error(function(data,header,config,status){
        });
    }


    //回到顶部
    $(".fiBtn").hide();
    $(window).on("scroll", function(){
        if($(window).scrollTop() >0){
            $(".fiBtn").show();
        }else{
            $(".fiBtn").hide();
        }
    });
    $scope.goBackTop=function () {
        $("body").animate({scrollTop: 0}, 300);
    };
    $scope.goBackTop();

}]);
